package com.lucian.ge.miniuser.controller;

import com.alibaba.fastjson.JSONObject;
import com.lucian.ge.comman.model.ResultMap;

import com.lucian.ge.util.JWTUtil;
import io.swagger.annotations.Api;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.net.URI;

/**
 * Created by Lucicol on 2019/6/4.
 */
@Api(value = "WxUserController", description = "微信小程序用户接口")
@RestController
@RequestMapping("/wxmini")
public class WxUserController {
    private final ResultMap resultMap;

    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.appsecret}")
    private String appsecret;

    private String openid;
    private String session_key;

    @Autowired
    public WxUserController( ResultMap resultMap) {
        this.resultMap = resultMap;
    }

    @GetMapping("/login")
//    @ResponseBody
    public ResultMap login(@RequestParam("code") String code) {
//        System.out.println(code);
//        System.out.println("appid=="+appid);

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        String url="https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+appsecret+"&js_code="+code+"&grant_type=authorization_code";
        try {
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();

            HttpGet httpGet = new HttpGet(uri);
            response = httpclient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(resultString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 解析json
        JSONObject jsonObject = (JSONObject) JSONObject.parse(resultString);
        session_key = jsonObject.get("session_key")+"";
        openid = jsonObject.get("openid")+"";

//        System.out.println("session_key=="+session_key);
//        System.out.println("openid=="+openid);

        return resultMap.success().code(200).message("微信授权成功").token("").res(resultString).data(null);
    }
}
